"use strict";
var e = this && this.__awaiter || function (e, t, o, i) {
    return new (o || (o = Promise))((function (n, r) {
        function a(e) {
            try {
                l(i.next(e))
            } catch (e) {
                r(e)
            }
        }

        function s(e) {
            try {
                l(i.throw(e))
            } catch (e) {
                r(e)
            }
        }

        function l(e) {
            var t;
            e.done ? n(e.value) : (t = e.value, t instanceof o ? t : new o((function (e) {
                e(t)
            }))).then(a, s)
        }

        l((i = i.apply(e, t || [])).next())
    }))
}, t = this && this.__importDefault || function (e) {
    return e && e.__esModule ? e : {default: e}
};
Object.defineProperty(exports, "__esModule", {value: !0}), exports.installService = void 0;
const o = require("../../../common/DbFactory"), i = require("../../../entity/PackageMetaData"),
    n = require("../../../common/FSFactory"), r = require("../../../utils/CommonUtil"),
    a = require("../../../utils/FsUtil"), s = t(require("path")), l = require("../../../utils/CommonConstants"),
    c = require("../../../packages/log");

function updateSnapshotVersions(versions) {
    const snapshotRegex = /^(.+)-SNAPSHOT\.(\d+)$/i;
    let snapshotsToUpdate = {};

    // Identify snapshots and group by main version
    for (let version in versions) {
        const match = version.match(snapshotRegex);
        if (match) {
            const mainVersion = match[1];
            const timestamp = parseInt(match[2], 10);
            if (!isNaN(timestamp)) {
                if (!snapshotsToUpdate[mainVersion] || snapshotsToUpdate[mainVersion].timestamp < timestamp) {
                    snapshotsToUpdate[mainVersion] = {timestamp, version};
                }
            }
        }
    }

    // Update versions object with the latest snapshot data
    for (const mainVersion in snapshotsToUpdate) {
        const latestSnapshot = snapshotsToUpdate[mainVersion].version;
        const snapshotVersion = `${mainVersion}-SNAPSHOT`;
        versions[snapshotVersion] = versions[latestSnapshot]
        versions[snapshotVersion]['version'] = snapshotVersion;
    }
}

exports.installService = new class {
    searchMetaByPackageName(t, c, d) {
        return e(this, void 0, void 0, (function* () {
            const e = yield o.commonDB.findById(i.OHPM_PACKAGE_METADATA_DB_NAME, r.CommonUtil.sha256(`${t}:${c}`));
            if (!e) return;
            const u = r.CommonUtil.genRandomTempDir();
            try {
                yield a.FsUtil.createDirIfNotExists(u);
                const t = s.default.join(u, "metadata.json"), o = yield n.FsFactory.getInstance(),
                    i = yield o.download(e.metaJsonFileId);
                yield r.CommonUtil.downloadUrl(i, t);
                const c = yield a.FsUtil.readJSON(t);
                updateSnapshotVersions(c.versions)
                return Object.values(c.versions).forEach((e => {
                    const t = e.dist.tarball;
                    if (e.dist.tarball = t.replace(l.DOWNLOAD_DOMAIN, d), e.dist.resolved_hsp) {
                        const t = e.dist.resolved_hsp;
                        e.dist.resolved_hsp = t.replace(l.DOWNLOAD_DOMAIN, d)
                    }
                })), c
            } finally {
                yield a.FsUtil.rm(u, {recursive: !0, force: !0})
            }
        }))
    }

    incrementDownloads(t, n) {
        return e(this, void 0, void 0, (function* () {
            try {
                const e = r.CommonUtil.sha256(`${t}:${n}`),
                    a = yield o.commonDB.findById(i.OHPM_PACKAGE_METADATA_DB_NAME, e);
                a.downloads++, yield o.commonDB.updateById(i.OHPM_PACKAGE_METADATA_DB_NAME, e, a, !0)
            } catch (e) {
                c.OhpmLazyLogger.error(`increment downloads error ! repoName: ${t}, packageName: ${n}, detail: ${e.message}.`)
            }
        }))
    }
};
